package dao.impl.comm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.comm.ITitleDAO;
import vo.comm.Title;

public class TitleDAOImpl implements ITitleDAO{
	private Connection conn=null;
	private PreparedStatement pstmt=null;
	public TitleDAOImpl(Connection conn){
		this.conn=conn;
	}
	public boolean doCreate(Title title) throws SQLException{
		boolean flag=false;
		String sql="INSERT INTO title(titlename)VALUES(?)";
		this.pstmt=this.conn.prepareStatement(sql);
		this.pstmt.setString(1, title.getTitlename());
		if(this.pstmt.executeUpdate()>0){
			flag=true;
		}
		this.pstmt.close();
		return flag;
	}
	public boolean doDelete(Title title) throws SQLException{
		boolean flag=false;
		String sql="DELETE FROM title WHERE titleid=? OR titlename=?";
		this.pstmt=this.conn.prepareStatement(sql);
		this.pstmt.setString(1, title.getTitleid());
		this.pstmt.setString(2, title.getTitlename());
		if(this.pstmt.executeUpdate()>0){
			flag=true;
		}
		if(this.pstmt!=null){
			this.pstmt.close();
		}
		return flag;
	}
	public Title findByName(String titlename) throws SQLException{
		Title title=null;
		String sql="SELECT titlename FROM title WHERE titlename=?";
		this.pstmt=this.conn.prepareStatement(sql);
		this.pstmt.setString(1,titlename);
		ResultSet rs=this.pstmt.executeQuery();
		if(rs.next()){
			title=new Title();
			title.setTitlename(rs.getString(1));
		}
		this.pstmt.close();
		return title;
	}
	public List<Title> findAll(String keyWord) throws SQLException{
		List<Title> all=new ArrayList<Title>();
		String sql="SELECT titleid,titlename FROM title WHERE titlename like ?";
		this.pstmt=this.conn.prepareStatement(sql);
		this.pstmt.setString(1, "%"+keyWord+"%");
		ResultSet rs=this.pstmt.executeQuery();
		Title title=null;
		while(rs.next()){
			title=new Title();
			title.setTitleid(rs.getString(1));
			title.setTitlename(rs.getString(2));
			all.add(title);
		}
		return all;
	}
	public boolean doUpdate(Title title) throws SQLException{
		boolean flag=false;
		String sql="UPDATE title SET titlename=? WHERE titleid=?";
		this.pstmt=this.conn.prepareStatement(sql);
		this.pstmt.setString(1, title.getTitlename());
		this.pstmt.setString(2, title.getTitleid());
		if(this.pstmt.executeUpdate()>0){
			flag=true;
		}
		if(this.pstmt!=null){
			this.pstmt.close();
		}
		return flag;
	}
}
